package com.huawei.file;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

/**
 * @description:
 * @author: lhh
 * @time: 2022/5/24
 */
public class DairyWindow extends JFrame {
    private JTextField jTextField;
    private JButton jButton;
    private JTextField jTextFieldShow;
    private JPanel jPanel;

    /**
     * Creates a new, initially invisible <code>Frame</code> with the
     * specified title.
     * <p>
     * This constructor sets the component's locale property to the value
     * returned by <code>JComponent.getDefaultLocale</code>.
     *
     * @param title the title for the frame
     * @throws HeadlessException if GraphicsEnvironment.isHeadless()
     *                           returns true.
     * @see GraphicsEnvironment#isHeadless
     * @see Component#setSize
     * @see Component#setVisible
     * @see JComponent#getDefaultLocale
     */
    public DairyWindow(String title) throws HeadlessException {
        super(title);
        init();//注意这个init一定要写！！！不然后面按钮无法出现！！
    }

    private void init(){
        jPanel = new JPanel();
        jTextField = new JTextField(20);
        jTextField.setSize(200,60);

        jTextFieldShow = new JTextField(20);//这里一定是Show 如果没有show运行时init报错
        jTextFieldShow.setSize(200,80);

        jButton = new JButton("submit");
        //匿名类
        jButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                File dairy = new File("./data/test.txt");
                if (!dairy.exists()){
                    try {
                        dairy.createNewFile();
                    } catch (IOException exception) {
                        exception.printStackTrace();
                    }
                }
                FileOperation operation = new FileOperationImpl();
                operation.fileWriter(dairy,jTextField.getText(),true);

                jTextFieldShow.setText(operation.fileReader(dairy));
            }
        });

        jPanel.add(jTextField);
        jPanel.add(jButton);
        jPanel.add(jTextFieldShow);

        setContentPane(jPanel);//画板和窗口绑定
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//窗口关闭
        setSize(300,300);
        setLocationRelativeTo(null);
    }
}
